// src/utils/websocket.js
import { ref, onUnmounted } from "vue";
import { updateMonitorData as returnUpdateMonitorData , tempInitMonitorData } from "@/utils/useMonitorData";
import {tempInitDeviceStatus  } from "@/utils/useDeviceData";
import { tempInitTemperatureData,mergeTemperatureData } from "@/utils/useTemperature";

// 正式环境是ws:127.0.0.1:10002
export function useWebSocket(url = import.meta.env.VITE_WS_URL, options = {}) {
  const socket = ref(null);
  const isConnected = ref(false);
  const reconnectAttempts = ref(0);
  // 最大重连次数
  const maxReconnectAttempts = options.maxReconnectAttempts || 5;
  // 重连间隔
  const reconnectInterval = options.reconnectInterval || 3000;
  const messageHandlers = new Map();

  // 状态数据（根据接口规范初始化）
  const deviceStatus = ref({
    sdcc_status: "close", // 湿电除尘状态
    ttxt_status: "close", // 脱硫系统状态
    scy_status: "close", // 数采仪工作状态
    fxy_status: "close", // 分析仪连接状态
    fxy_wd_status: "close", // 分析仪温度报警
    ph_status: "--", // ph数值
    sb_1: "close", // 1号水泵
    sb_2: "close", // 2号水泵
    sb_3: "close", // 3号水泵
    sb_4: "close", // 4号水泵
  });
  // 实时监测数据（新增data类型）
  const monitorData = ref(tempInitMonitorData);

  const temperatureData = ref(tempInitTemperatureData);
  let heartbeatTimer = null;
  let reconnectTimer = null;

  // 初始化WebSocket连接
  const connect = () => {
    socket.value = new WebSocket(url);

    socket.value.onopen = () => {
      console.log("WebSocket connected");
      isConnected.value = true;
      // 发送token
      send("login", { token: localStorage.getItem("token") });
      reconnectAttempts.value = 0;
      // 不用主动发
      // startHeartbeat()
    };

    socket.value.onmessage = (event) => {
      try {
        const message = JSON.parse(event.data);
        handleMessage(message);
      } catch (error) {
        console.error("WebSocket message parse error:", error);
      }
    };

    socket.value.onclose = () => {
      console.log("WebSocket disconnected");
      isConnected.value = false;
      stopHeartbeat();
      attemptReconnect();
    };

    socket.value.onerror = (error) => {
      console.error("WebSocket error:", error);
    };
  };

  // 消息处理
  const handleMessage = (message) => {
    console.log(
      "%c [ message.type ]-67",
      "font-size:18px; background:#570eff; color:#9b52ff;",
      message.type
    );
    switch (message.type) {
      case "ping":
        sendPong();
        break;
      case "config":
        updateDeviceStatus(message.payload);
        break;
      case "data":
        updateMonitorData(message.payload);
        break;
      case "temperature":
        // debugger
        const newData = mergeTemperatureData(temperatureData.value, message.payload)
        temperatureData.value = newData
        break;
      default:

        // 触发自定义消息处理器
        if (messageHandlers.has(message.type)) {
          messageHandlers.get(message.type)(message.payload);
        }
    }
  };

  // 更新设备状态
  const updateDeviceStatus = (payload) => {
    deviceStatus.value = {
      ...deviceStatus.value,
      ...payload,
    };
  };
  const updateMonitorData = (payload) => {
    monitorData.value = returnUpdateMonitorData(payload);
  };
  // 心跳机制
  const startHeartbeat = () => {
    heartbeatTimer = setInterval(() => {
      if (isConnected.value) {
        socket.value.send(JSON.stringify({ type: "pong" }));
      }
    }, 30000); // 30秒一次心跳
  };

  const stopHeartbeat = () => {
    if (heartbeatTimer) {
      clearInterval(heartbeatTimer);
      heartbeatTimer = null;
    }
  };

  const sendPong = () => {
    if (isConnected.value) {
      socket.value.send(JSON.stringify({ type: "pong" }));
    }
  };

  // 重连机制
  const attemptReconnect = () => {
    if (reconnectAttempts.value < maxReconnectAttempts) {
      reconnectAttempts.value++;
      console.log(
        `Reconnecting... Attempt ${reconnectAttempts.value}/${maxReconnectAttempts}`
      );

      reconnectTimer = setTimeout(() => {
        connect();
      }, reconnectInterval);
    } else {
      console.error("Max reconnection attempts reached");
    }
  };

  // 发送消息
  const send = (type, payload) => {
    if (isConnected.value) {
      socket.value.send(JSON.stringify({ type, payload }));
    } else {
      console.error("WebSocket is not connected");
    }
  };

  // 注册消息处理器
  const on = (type, handler) => {
    messageHandlers.set(type, handler);
  };

  // 清理
  const disconnect = () => {
    if (socket.value) {
      socket.value.close();
    }
    stopHeartbeat();
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
    }
  };

  // 自动连接
  connect();

  // 组件卸载时自动清理
  onUnmounted(() => {
    disconnect();
  });

  return {
    isConnected,
    deviceStatus,
    monitorData,
    temperatureData,
    send,
    on,
    disconnect,
  };
}
